package com.nineshadow.games.entity;

import cn.stylefeng.guns.modular.system.model.GameUser;
import com.nineshadow.games.constants.CommonConstants;
import com.nineshadow.games.interfaces.IGameUser;
import com.nineshadow.games.launch.GameWorld;
import com.nineshadow.games.launch.HallServer;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * <p>
 * 通用游戏用户
 * </p>
 *
 * @author ting liu
 * @since 2018/12/3 14:07
 */
@Slf4j
public class CommonGameUser implements IGameUser {

    /**
     * 数据库用户信息
     */
    protected volatile GameUser userInfo;
    /**
     * 会话
     */
    protected volatile ChannelHandlerContext ctx;

    private String lastRoomId;

    private PollHandler pollHandler;

    @Override
    public GameUser getUserInfo() {
        return userInfo;
    }

    @Override
    public void setUserInfo(GameUser userInfo) {
        this.userInfo=userInfo;
    }

    @Override
    public int getUserId() {
        return userInfo.getId();
    }

    @Override
    public String getNickName() {
        return userInfo.getNickName();
    }

    @Override
    public ChannelHandlerContext getCtx() {
        return this.ctx;
    }

    @Override
    public void setCtx(ChannelHandlerContext ctx) {
        this.ctx=ctx;
    }


    @Override
    public void offline(ChannelHandlerContext ctx) {
        GameWorld.quitLoginUser(getUserId());
        removeUserInfo();
    }

    @Override
    public void removeUserInfo() {
        //删除redis中用户数据
        HallServer.redisUtil.del(CommonConstants.USER + getUserId());
        //终止轮询
        removePollHandler();
    }

    @Override
    public void setLastRoomId(String roomId) {
        this.lastRoomId=roomId;
    }

    @Override
    public String getLastRoomId() {
        return this.lastRoomId;
    }


    @Override
    public PollHandler getPollHandler() {
        return pollHandler;
    }

    @Override
    public void setPollHandler(PollHandler pollHandler) {
        this.pollHandler = pollHandler;
    }

    public void removePollHandler(){
        if(Objects.nonNull(pollHandler)){
            pollHandler.setDone(true);
            setPollHandler(null);
        }
        HallServer.redisUtil.del(CommonConstants.USER_POLL_QUEUE + getUserId());
    }

}
